<template>
	<view class="page" v-if="true">
		<view class="pay-price">
			<view class="price">
				<text class="unit">￥</text>
				<!-- <numberScroll :num='payPriceShow' color="#E93323" width='30' height='50' fontSize='50'></numberScroll> -->
				<u-count-to :endVal="orderPrice" separator="," color="#E93323" duration="500" decimals="2"></u-count-to>
			</view>
			<!-- <view class="count-down">
				支付剩余时间：
				<u-count-down :time="30 * 60 * 60 * 1000" format="HH:mm:ss"></u-count-down>
			</view> -->
		</view>
		<view class="payment">
			<view class="title">
				支付方式
			</view>
			<view class="item flex-between" v-for="(item,index) in cartArr" :key="index" v-show='item.payStatus'
				@click="payType(item.number || 0, item.value, index)">
				<view class="left flex-between">
					<u-icon class="iconfont" custom-prefix="custom-icon" :name="item.icon" size="21"
						:color="item.color"></u-icon>
					<view class="text  flex-col">
						<view class="name">{{item.name}}</view>
						<view class="info" v-if="item.value == 'yue'">
							{{item.title}} <span class="money">￥{{ item.number }}</span>
						</view>
						<view class="info" v-else>{{item.title}}</view>
					</view>
				</view>
				<u-icon custom-prefix="custom-icon" style="margin-right: 10rpx;"
					:name="active==index ? 'gouxuan':'weigouxuan'" size="18" color="#FF4110"></u-icon>
				<!-- <view class="iconfont" :class="active==index?'icon-xuanzhong11 font-num':'icon-weixuan'"></view> -->
			</view>
		</view>
		<view class="btn">
			<view class="button flex-center" @click='$u.throttle(goPay(orderPrice), 500)'>确认支付</view>
			<!-- <view class="button flex-center" @click='$u.throttle(goPay(number, paytype), 500)'>确认支付</view> -->
			<!-- <view class="wait-pay" @click="$u.throttle(waitPay, 500)">暂不支付</view> -->
			<view class="wait-pay" @click="$u.throttle(cancelOrder, 500)">取消订单</view>
		</view>
		<view v-show="false" v-html="formContent"></view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		watch
	} from "vue"
	import API from "@/api/index.js"
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		toast
	} from "@/uni_modules/uview-plus";
	onShow(() => {
		let options = wx.getEnterOptionsSync();
		if (options.scene == '1038' && options.referrerInfo.appId == 'wxef277996acc166c3' && initIn.value) {
			// 代表从收银台小程序返回
			let extraData = options.referrerInfo.extraData;
			initIn.value = false
			if (!extraData) {
				// "当前通过物理按键返回，未接收到返参，建议自行查询交易结果";
				this.$util.Tips({
					title: this.$t(`取消支付`)
				}, {
					tab: 5,
					url: `/pages/goods/order_pay_status/index?order_id=${this.orderId}&msg=${this.$t(`取消支付`)}&type=3&totalPrice=${this.payPriceShow}&status=2`
				});
			} else {
				if (extraData.code == 'success') {
					this.$util.Tips({
						title: this.$t(`支付成功`),
						icon: 'success'
					}, {
						tab: 5,
						url: `/pages/goods/order_pay_status/index?order_id=${this.orderId}&msg=${this.jumpData.msg}&type=3&totalPrice=${this.payPriceShow}`
					});
				} else if (extraData.code == 'cancel') {
					// "支付已取消";
					this.$util.Tips({
						title: this.$t(`取消支付`)
					}, {
						tab: 5,
						url: `/pages/goods/order_pay_status/index?order_id=${this.orderId}&msg=${this.$t(`取消支付`)}&type=3&totalPrice=${this.payPriceShow}&status=2`
					});
				} else {
					// "支付失败：" + extraData.errmsg;
					uni.reLaunch({
						url: `/pages/goods/order_pay_status/index?order_id=${this.orderId}&msg=${this.$t(`支付失败`)}&totalPrice=${this.payPriceShow}`
					})
				}
			}
		}
	})

	onLoad((options) => {
		console.log("options",options);
		if (options.order_id) orderId.value = options.order_id
		if (options.price) orderPrice.value = options.price
		if (options.routeDistance) routeDistance.value = options.routeDistance
		if (options.addressData) addressData = JSON.parse(options.addressData) 
		if (options.proInfo) proInfo = JSON.parse(options.proInfo) 
		// if (options.from_type) fromType.value = options.from_type
	})
	/* 支付方式 */
	const cartArr = reactive([{
			"name": `微信支付`,
			"icon": "weixin",
			color: "#09bb07",
			value: 'weixin',
			title: `使用微信快捷支付`,
			payStatus: 1,
		},
		// {
		// 	"name": `支付宝支付`,
		// 	"icon": "zhifubao",
		// 	color: "#00aaea",
		// 	value: 'alipay',
		// 	title: `使用支付宝支付`,
		// 	payStatus: 1,
		// },
		// {
		// 	"name": `余额支付`,
		// 	"icon": "yue",
		// 	color: "#ff9900",
		// 	value: 'alipay',
		// 	title: `使用支付宝支付`,
		// 	payStatus: 1,
		// },
	])

	const checked = ref(false)
	const datatime = ref(1676344056)
	/* 订单ID */
	const orderId = ref(0);
	const orderPrice = ref(0);
	const routeDistance = ref(0);
	let proInfo = reactive({});
	let addressData = reactive({});

	const fromType = ref('')
	const active = ref(0)
	const payPrice = ref(0)
	const payPriceShow = ref(0)

	const payPostage = ref(0)
	const offlinePostage = ref(false)
	const invalidTime = ref(0)

	const initIn = ref(false)
	const jumpData = ref({
		orderId: '',
		msg: ''
	})
	const formContent = ref('')

	const oid = ref(0)
	const paytype = ref('')
	const number = ref(0)
	const payType = (n, p, index) => {
		active.value = index;
		paytype.value = p;
		number.value = n;
		console.log("payType", n, p, index);
	}

	const waitPay = () => {
		uni.reLaunch({
			url: '/pages/goods/order_pay_status/index?order_id=' + orderId.value + '&msg=取消支付&type=3' +
				'&status=2&totalPrice=' + orderPrice.value
		})
	}
	// 取消订单
	const cancelOrder = () => {

	}
	// 分配派送员
	const deliveryOrder = async () => {
		let id = await API.uuid()
		let user = uni.getStorageSync('userInfo')
		let data = JSON.stringify({
			// 后台修改信息 必要字段------------------
			Id: user.id ? user.id : id.data,
			// Id:id.data,
			RegisterUserId: user.id,
			RegisterDeptId: user.deptId,
			RegisteTime: user.registeTime,
			editUserId: user.id,
			EditTime: +new Date(),
			RegisterInfo: null,
			EditUserInfo: null,
			RegisterDept: null,
			// --------------------------
			"delivery": [{
				"id": 0,
				"no": orderId.value,
				"mileage": routeDistance.value,
				"price": orderPrice.value,
				"lat": proInfo.lat,
				"lng": proInfo.lng,
				"address": addressData.province+''+addressData.city+''+addressData.address
			}],
			"describe": "string",
			// "userId": uni.getStorageSync('userInfo').id,
			"recTime": +new Date(),
			"state": "等待加油",
			"gasStationId": proInfo.id,
			"lat": proInfo.lat,
			"lng": proInfo.lng,
			"addressCode": "",
			"gasStationInfo": proInfo,
			"userInfo": null

		})
		let res = await API.DeliveryOrder(data)
		console.log("分配派送员", data, res);
	}
	const goPay = async () => {
		console.log("goPay", orderId.value, orderPrice.value);
		// 1. 请求后端创建支付订单
		// const res = await uni.request({
		//   url: 'https://your-server.com/api/createOrder',
		//   method: 'POST',
		//   data: {
		//     openid: uni.getStorageSync('openid'), // 用户openid
		//     total_fee: orderInfo.totalFee, // 金额(单位分)
		//     body: orderInfo.body, // 商品描述
		//     out_trade_no: orderInfo.outTradeNo // 商户订单号
		//   }
		// });

		// 2. 获取支付参数
		// const paymentData = res.data.data;

		// 3. 调用微信支付
		// const paymentRes = await uni.requestPayment({
		//   provider: 'wxpay',
		//   timeStamp: paymentData.timeStamp,
		//   nonceStr: paymentData.nonceStr,
		//   package: paymentData.package,
		//   signType: paymentData.signType,
		//   paySign: paymentData.paySign,
		//   success: (res) => {
		//     console.log('支付成功', res);
		//     // 支付成功后的业务逻辑
		//   },
		//   fail: (err) => {
		//     console.error('支付失败', err);
		//     // 支付失败处理
		//   }
		// });
		if(addressData!=null){
			// 如果为派送单
			deliveryOrder()
		}
		
		// 仅作为示例，非真实参数信息。
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: String(Date.now()),
			nonceStr: 'A1B2C3D4E5',
			package: 'prepay_id=wx20180101abcdefg',
			signType: 'MD5',
			paySign: 'MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111) = 22D9B4E54AB1950F51E0649E8810ACD6',
			success: function(res) {
				console.log('success:' + JSON.stringify(res));
			},
			fail: function(err) {
				console.log('fail:' + JSON.stringify(err));
			}
		});
		// if (!orderId.value) return toast('请选择要支付的订单')
		// if (paytype.value == 'yue' && parseFloat(number) < parseFloat(payPriceShow.value)) return toast('余额不足')
		// uni.showLoading({
		// 	title: "支付中"
		// });

		// try {
		// 	const res = await orderPay({
		// 		orderId: orderId.value,
		// 		paytype: paytype.value,
		// 	})

		// 	// 状态 订单id
		// 	let status = res.data.status,
		// 		orderId = res.data.result.order_id,
		// 		goPages = '/pages/goods/order_pay_status/index?order_id=' + this.orderId + '&msg=' +
		// 		res
		// 		.msg +
		// 		'&type=3' + '&totalPrice=' + this.payPriceShow,
		// 		friendPay = '/pages/users/payment_on_behalf/index?order_id=' + this.orderId +
		// 		'&spread=' +
		// 		this
		// 		.$store.state.app.uid,
		// 		jsConfig = res.data.jsConfig
		// 	switch (status) {
		// 		case 'ORDER_EXIST':
		// 		case 'EXTEND_ORDER':
		// 			uni.hideLoading();
		// 			return uni.showToast({
		// 				title: res.msg,
		// 				success() {
		// 					uni.redirectTo({
		// 						url: goPages
		// 					})
		// 				}
		// 			})
		// 		case 'ALLINPAY_PAY':
		// 			uni.hideLoading();
		// 			// #ifdef MP
		// 			initIn.value = true
		// 			wx.openEmbeddedMiniProgram({
		// 				appId: 'wxef277996acc166c3',
		// 				extraData: {
		// 					cusid: jsConfig.cusid,
		// 					appid: jsConfig.appid,
		// 					version: jsConfig.version,
		// 					trxamt: jsConfig.trxamt,
		// 					reqsn: jsConfig.reqsn,
		// 					notify_url: jsConfig.notify_url,
		// 					body: jsConfig.body,
		// 					remark: jsConfig.remark,
		// 					validtime: jsConfig.validtime,
		// 					randomstr: jsConfig.randomstr,
		// 					paytype: jsConfig.paytype,
		// 					sign: jsConfig.sign,
		// 					signtype: jsConfig.signtype
		// 				}
		// 			})
		// 			this.jumpData = {
		// 				orderId: res.data.result.order_id,
		// 				msg: res.msg,
		// 			}
		// 			// #endif


		// 			break;
		// 		case 'PAY_ERROR':
		// 			uni.hideLoading();
		// 			return uni.showToast({
		// 				title: res.msg,
		// 				success() {
		// 					uni.redirectTo({
		// 						url: goPages
		// 					})
		// 				}
		// 			})
		// 			break;
		// 		case 'SUCCESS':
		// 			uni.hideLoading();
		// 			return uni.showToast({
		// 				title: res.msg,
		// 				success() {
		// 					uni.reLaunch({
		// 						url: goPages
		// 					})
		// 				}
		// 			})

		// 			break;
		// 		case 'WECHAT_PAY':
		// 			toPay.value = true;
		// 			// #ifdef MP
		// 			/* that.toPay = true; */
		// 			let mp_pay_name = ''
		// 			if (uni.requestOrderPayment) {
		// 				mp_pay_name = 'requestOrderPayment'
		// 			} else {
		// 				mp_pay_name = 'requestPayment'
		// 			}
		// 			uni[mp_pay_name]({
		// 				timeStamp: jsConfig.timestamp,
		// 				nonceStr: jsConfig.nonceStr,
		// 				package: jsConfig.package,
		// 				signType: jsConfig.signType,
		// 				paySign: jsConfig.paySign,
		// 				success: function(res) {
		// 					uni.hideLoading();
		// 					if (BargainId.value || combinationId.value || pinkId.value ||
		// 						seckillId.value || discountId.value) {
		// 						return uni.showToast({
		// 							title: res.msg,
		// 							success() {
		// 								uni.reLaunch({
		// 									url: goPages
		// 								})
		// 							}
		// 						})

		// 					}
		// 					return uni.showToast({
		// 						title: res.msg,
		// 						success() {
		// 							uni.redirectTo({
		// 								url: goPages
		// 							})
		// 						}
		// 					})
		// 				},
		// 				fail: function(e) {
		// 					uni.hideLoading();
		// 					return uni.showToast({
		// 						title: "取消支付",
		// 						success() {
		// 							uni.redirectTo({
		// 								url: goPages + '&status=2'
		// 							})
		// 						}
		// 					})
		// 				},
		// 				complete: function(e) {
		// 					uni.hideLoading();
		// 					//关闭当前页面跳转至订单状态
		// 					if (res.errMsg == 'requestPayment:cancel' || e.errMsg ==
		// 						'requestOrderPayment:cancel') return
		// 					uni.showToast({
		// 						title: "取消支付",
		// 						success() {
		// 							uni.redirectTo({
		// 								url: goPages + '&status=2'
		// 							})
		// 						}
		// 					})
		// 				},
		// 			})
		// 			// #endif
		// 			break;
		// 		case 'PAY_DEFICIENCY':
		// 			uni.hideLoading();
		// 			//余额不足
		// 			return
		// 			uni.showToast({
		// 				title: res.msg,
		// 				success() {
		// 					uni.redirectTo({
		// 						url: goPages + '&status=1'
		// 					})
		// 				}
		// 			})

		// 			break;


		// 		case 'ALIPAY_PAY':

		// 			// #ifdef MP
		// 			uni.navigateTo({
		// 				url: `/pages/users/alipay_invoke/index?id=${orderId}&link=${jsConfig.qrCode}`
		// 			});
		// 			// #endif

		// 			break;
		// 	}
		// } catch {
		// 	uni.hideLoading();
		// 	uni.showToast({
		// 		title: '支付失败',
		// 	})

		// }
	}
</script>

<style lang="scss" scoped>
	.page {
		.pay-price {
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			padding: 50rpx 0 40rpx 0;

			.price {
				color: #E93323;
				margin-bottom: 20rpx;
				display: flex;
				align-items: flex-end;

				.unit {
					font-size: 34rpx;
					font-weight: 500;
					line-height: 41rpx;
				}

				.num {
					font-size: 50rpx;
					font-weight: 600;
				}
			}

			.count-down {
				:deep(.u-count-down__text) {
					font-size: 24rpx;
					color: #E93323;
				}

				display: flex;
				align-items: center;
				background-color: #fff;
				padding: 8rpx 28rpx;
				border-radius: 40rpx;
				font-size: 24rpx;
				color: #E93323;

				.time {
					margin-top: 0 !important;
				}


			}
		}

		.payment {
			width: 690rpx;
			border-radius: 14rpx 14rpx;
			background-color: #fff;
			z-index: 999;
			margin: 0 30rpx;

			.title {
				color: #666666;
				font-size: 26rpx;
				padding: 30rpx 0 0 30rpx;
			}

			.payMoney {
				font-size: 28rpx;
				color: #333333;
				text-align: center;
				margin-top: 50rpx;

				.font-color {
					margin-left: 10rpx;

					.money {
						font-size: 40rpx;
					}
				}
			}


		}

		.payment.on {
			transform: translate3d(0, 0, 0);
		}

		.icon-xuanzhong11 {
			color: #E93323 !important;
		}

		.payment .item {
			border-bottom: 1rpx solid #eee;
			height: 130rpx;
			margin-left: 30rpx;
			padding-right: 30rpx;
		}

		.payment .item:last-child {
			border-bottom: none;
		}

		.payment .item .left {
			flex: 1;
		}

		.payment .item .left .text {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;
		}

		.payment .item .left .text .name {
			font-size: 30rpx;
			color: #333;
		}

		.payment .item .left .text .info {
			font-size: 22rpx;
			color: #999;
		}

		.payment .item .left .text .info .money {
			color: #ff9900;
		}

		.payment .item .left .iconfont {
			font-size: 50rpx;
			color: #09bb07;
			margin-right: 28rpx;
		}

		.payment .item .left .iconfont.icon-zhifubao {
			color: #00aaea;
		}

		.payment .item .left .iconfont.icon-yuezhifu {
			color: #ff9900;
		}



		.payment .item .iconfont {
			font-size: 40rpx;
			color: #ccc;
		}

		.icon-haoyoudaizhifu {
			color: #F34C3E !important;
		}

		.btn {
			position: fixed;
			left: 30rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			bottom: 30rpx;
			bottom: calc(30rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
			bottom: calc(30rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
		}

		.wait-pay {
			color: #aaa;
			font-size: 24rpx;
			padding-top: 20rpx;
		}

		.button {
			width: 690rpx;
			height: 90rpx;
			border-radius: 45rpx;
			color: #FFFFFF;
			background-color: #E93323;

		}

	}
</style>